package com.example.swimmingpool.service.goods;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.swimmingpool.entity.goods.Goods;
import com.example.swimmingpool.entity.goods_type.GoodsType;
import com.example.swimmingpool.mapper.goods.GoodsMapper;
import com.example.swimmingpool.qo.goods.GoodsQo;
import com.example.swimmingpool.vo.goods.GoodsGroupByTypeVo;
import com.example.swimmingpool.vo.goods.GoodsVo;
import com.example.swimmingpool.vo.goods_type.GoodsTypeVo;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class GoodsService extends ServiceImpl<GoodsMapper, Goods> {
    public int update(GoodsVo vo) {
        var goods = BeanUtil.copyProperties(vo, Goods.class);
        return this.getBaseMapper().updateById(goods);

    }

    public IPage<GoodsVo> getPages(GoodsQo qo) {
        IPage<Goods> pages = new LambdaQueryChainWrapper<>(this.getBaseMapper())
                .eq(ObjectUtil.isNotNull(qo.getId()), Goods::getId, qo.getId())
                .like(StrUtil.isNotBlank(qo.getTypeKey()), Goods::getTypeKey, qo.getTypeKey())
                .like(StrUtil.isNotBlank(qo.getName()), Goods::getName, qo.getName())
                .last(StrUtil.isNotBlank(qo.getSort()), String.format("order by %s", qo.getSort()))
                .page(new Page<>(qo.getCurrent(), qo.getSize()));

        return pages.convert(goods -> BeanUtil.copyProperties(goods, GoodsVo.class));

    }

    public List<GoodsGroupByTypeVo> getGoodsToUser() {
        return new LambdaQueryChainWrapper<>(this.getBaseMapper())
                .list()
                .stream()
                .map(goods -> BeanUtil.copyProperties(goods, GoodsVo.class))
                .collect(Collectors.groupingBy(GoodsVo::getTypeKey))
                .entrySet()
                .stream()
                .map(e -> new GoodsGroupByTypeVo(e.getKey(), e.getValue()))
                .toList();

    }
}
